<?php
/**
 * Created by IntelliJ IDEA.
 * User: 张伯发
 * Date: 2019/8/1
 * Time: 11:05
 */

namespace App\Http\Controller\Happy;


use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use Swoft\Redis\Pool;

/**
 * @Controller("happy/redis")
 * Class RedisController
 * @package App\Http\Controller\Happy
 * @author 张伯发 2019/8/1 11:05
 */
class RedisController
{
    /**
     * @Inject()
     * @var Pool
     */
    private $redis;


    /**
     * @RequestMapping(route="set", method={RequestMethod::GET})
     * @param Request $request
     * @return array
     * @author 张伯发 2019/8/1 11:09
     */
    public function set(Request $request): array
    {
        $name = $request->get("name", "hello");
        $result = $this->redis->set("name", $name);
        return ['result' => $result];
    }


    /**
     * @RequestMapping("get")
     * @param Request $request
     * @return array
     * @author 张伯发 2019/8/1 11:37
     */
    public function get(Request $request): array
    {
        $key = $request->get("key", 'name');
        $result = $this->redis->get($key);
        return ['result' => $result];
    }


    /**
     * @RequestMapping("setArray")
     * @return array
     * @author 张伯发 2019/8/1 11:41
     */
    public function setArray(): array
    {
        $result = $this->redis->set("test-array", ['username' => 'zhagnsan', 'age' => 20]);
        return ['result' => $result];
    }


    /**
     * @RequestMapping("getArray")
     * @return array
     * @author 张伯发 2019/8/1 11:45
     */
    public function getArray(): array
    {
        $result = $this->redis->get("test-array");
        return ['result' => $result];
    }


    /**
     * 管道，一个操作中向服务器发送很多命令
     *
     * @RequestMapping("pipeline")
     * @return array
     * @author 张伯发 2019/8/1 13:28
     */
    public function pipeline() : array
    {
        $count = 10;
        $result = $this->redis->pipeline(function (\Redis $redis) use ($count) {

            for ($i = 0; $i < $count; $i++) {
                $redis->set("key:$i", $i);
            }
        });
        return ['result' => $result];
    }

}
